import requests
import json
import os
import shutil


# 包含的接口
# 2.1.1.1 查询  接口   正常
# 2.1.1.2 查询  已找到  正常
# 2.1.1.3 查询  已找到  正常
# 2.1.1.4       接口  提示url不存在
# 2.1.1.5      已找到  报错
# 2.1.1.6      接口    好像有点问题，是空  重点
# 2.1.5.1 查询   接口   提示url不存在
# 2.1.6.1 查询  已找到  正常
# 2.1.6.2       接口      数据构建         重点
# 2.1.7.1 查询  接口   提示url不存在
# 2.1.8.1 查询  已找到   正常
# 2.1.8.2 查询  接口     正常
# 2.1.8.3 查询  接口    好像有点问题，是空   重点
# 2.1.8.5      接口     提示url不存在
# 2.1.8.6      接口    好像有点问题，是空   重点
# 2.1.8.7       已找到  正常
# 2.1.8.8       已找到  正常
# 2.1.8.9       已找到  正常
# 2.1.9.1 查询   接口   提示url不存在

# bug251  bug209已修复
# bug248   302未修复

# 打印HTTP响应消息的函数
def printResponse(response):
    print('\n\n-------- HTTP response * begin -------')
    print(response.status_code)

    for k, v in response.headers.items():
        print(f'{k}: {v}')

    print('')

    print(response.content.decode('utf8'))
    print('-------- HTTP response * end -------\n\n')
# 打印请求消息， 参数为 PreparedRequest 对象
def pretty_print_request(req):
    if req.body == None:
        msgBody = ''
    else:
        msgBody = req.body
    print(
        '{}\n{}\n{}\n\n{}'.format(
        '\n\n----------- 发送请求 -----------',
        req.method + ' ' + req.url,
        '\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
        msgBody,
    ))
#定义一个发请求的函数
def sendApiRequest(url,header,para):
    real_url = HOST+APPLICATION+url
    req = requests.Request(
        'Post',
        real_url,
        header,
        data=json.dumps(para)
    )
    prepared = s.prepare_request(req)
    resp = s.send(prepared)
    # printResponse(resp)
    return [resp.text,resp,prepared]

#定义了一个导出返回消息的
import time
def json_to_file(resp_list,api_name):
    json_str = resp_list[0]
    data = json.loads(json_str)
    # timestamp = int(time.time())
    timestamp = time.strftime('%Y-%m-%d__%H_%M_%S', time.localtime())
    file_name = f"({resp_list[1].status_code})接口{api_name}_{timestamp}.txt"

    #创建一个临时的文件夹
    os.makedirs('tmp', exist_ok=True)

    with open(f'tmp/{file_name}', "w", encoding="utf-8") as f:
        if resp_list[1].status_code == 100:
            f.write(json.dumps(data, indent=4, ensure_ascii=False))
        else:
            f.write(json.dumps(data, indent=4, ensure_ascii=False)+'\n'+
                    '{}\n{}\n{}\n\n'.format(
                        '\n\n----------- 发送请求 -----------',
                        resp_list[2].method + ' ' + resp_list[2].url,
                        '\n'.join('{}: {}'.format(k, v) for k, v in resp_list[2].headers.items()),
                    )+
                    '{}\nHTTP/1.1 {}\n{}\n\n{}'.format(
                        '\n\n----------- 得到响应 -----------',
                        resp_list[1].status_code,
                        '\n'.join('{}: {}'.format(k, v) for k, v in resp_list[1].headers.items()),
                        resp_list[1].text,)
                    )

    return file_name


# 登录的接口，不能变
HOST = "http://10.202.81.50:8080"
APPLICATION = "/api/fs-kone"
s = requests.Session()

#提交app信息，获取token1
url = "/biz/param/findParamConfig"
log_playload = {
           'appid': 'fs-kone',
           'paraid': 'plugin.install'
       }

req = requests.Request(
    'Post',
    HOST+APPLICATION+url,
    headers={
        'Content-Type':'application/json',
    },
    data=json.dumps(log_playload)
)
prepared = s.prepare_request(req)
# pretty_print_request(prepared)
r1 = s.send(prepared)
# printResponse(r1)

#登录，获取到token2

url = "/auth/login"

password_playload = {
           'username': '8888',
           'password': '607Bi0eWBeHJ9hGiE3/jJA==',
            'veriCode':'',
            'client_id':'fs-kone',
            'logtype':'0'
       }

req = requests.Request(
    'Post',
    HOST+APPLICATION+url,
    headers={
        'Content-Type':'application/json',
    },
    data=json.dumps(password_playload)
)

prepared = s.prepare_request(req)
# pretty_print_request(prepared)
r2 = s.send(prepared)
# printResponse(r2)
# print(r2.json())

# 要带上access_token
ACCESS_TOKEN = r2.json()['body'][0]['access_token']
# print(f'代码103行，access_token是{ACCESS_TOKEN}')

headers = {
    'Content-Type':'application/json',
    'Authorization' : f'Bearer {ACCESS_TOKEN}'
}
#删除生成的结果文件
if os.path.exists('tmp'):
    shutil.rmtree('tmp', ignore_errors=True)


# # 对接口发送请求(可以梗概接口)
HOST = 'http://10.201.69.36:9092'
APPLICATION = ''

                                    # 开始查询接口的测试
# 2.1.1.1 查询
API = '2.1.1.1'
url = '/rbac/menu/findMenuList'
inter4 = {
    'operid': 8888
}
resp4 = sendApiRequest(url, headers, inter4)
json_to_file(resp4, API)
#
# 2.1.1.2 查询
API = '2.1.1.2E'
url = '/rbac/menu/findMenuListByRoleId'
inter5 = {
    'operid': 8888,
    'righttype':'E'
}
resp5 = sendApiRequest(url, headers, inter5)
json_to_file(resp5, API)

API = '2.1.1.2G'
url = '/rbac/menu/findMenuListByRoleId'
inter6 = {
    'operid': 8888,
    'righttype':'G'
}
resp6 = sendApiRequest(url, headers, inter6)
json_to_file(resp6, API)

# 2.1.1.3 查询
API = '2.1.1.3'
url = '/rbac/api/findApiByRoleid'
inter7 = {
    'operid': 8888
}
resp7 = sendApiRequest(url, headers, inter7)
json_to_file(resp7, API)

# 2.1.5.1 查询
API = '2.1.5.1ap'
url = '/rbac/dict/findByDictCode'
inter8 = {
    'operid': 8888,
    'dictCode':'status'
}
resp8 = sendApiRequest(url, headers, inter8)
json_to_file(resp8,API)

API = '2.1.5.1op'
url = '/rbac/dict/findByDictCode'
inter8 = {
    'operid': 8888,
    'dictCode':'citizenship'
}
resp8 = sendApiRequest(url, headers, inter8)
json_to_file(resp8,API)

API = '2.1.5.1'
url = '/rbac/dict/findByDictCode'
inter8 = {
    'operid': 8888,
    'dictCode':''
}
resp8 = sendApiRequest(url, headers, inter8)
json_to_file(resp8,API)
# 2.1.6.1 查询
API = '2.1.6.1'
url = '/rbac/operator/findSignOperListByRoleId'
inter8 = {
    'roleid': 2
}
resp8 = sendApiRequest(url, headers, inter8)
json_to_file(resp8,API)

API = '2.1.6.1_8888'
url = '/rbac/operator/findSignOperListByRoleId'
inter8 = {
    'roleid': 1
}
resp8 = sendApiRequest(url, headers, inter8)
json_to_file(resp8,API)
# 2.1.7.1 查询

API = '2.1.7.1'
url = '/rbac/org/findOrgs'
inter8 = {
    'operid': 8888,
}
resp8 = sendApiRequest(url, headers, inter8)
json_to_file(resp8,API)

API = "2.1.8.1"
# 例：http://10.202.81.50:8080/api/fs-kone/rbac/rightdata/operDatarightRole   post请求
url = "/rbac/rightdata/operDatarightRole"
inter1 = {
    'pageSize': 200,
    'pageNum':1,
    'operid': 8888,
}
resp1 = sendApiRequest(url,headers,inter1)
json_to_file(resp1,API)


API = "2.1.8.2"
url = "/rbac/role/findOperRoleList"
inter2 = {
    'operid': 16031
}
resp2 = sendApiRequest(url, headers, inter2)
json_to_file(resp2, API)


API = '2.1.8.3'
url = '/rbac/role/findRoleListByOperId'
inter3 = {
    'targetoperid': 16031
}
resp3 = sendApiRequest(url, headers, inter3)
json_to_file(resp3, API)


# 2.1.9.1 查询
API = '2.1.9.1'
url = '/system/upgradeList'
inter8 = {
    'operid': 8888,
}
resp8 = sendApiRequest(url, headers, inter8)
json_to_file(resp8,API)



                                        # 下面的接口都涉及到修改
# # 2.1.1.4
# API ='2.1.1.4新增'
# url = '/rbac/menu/batchUpdMenuRtres'
# inter8 = [{'rightType':'E', 'menuId':'10001010', 'objCode':4, 'objType':'1', 'action':'1'}]
# resp8 = sendApiRequest(url, headers, inter8)
# json_to_file(resp8,API)
#
# API ='2.1.1.4删除'
# url = '/rbac/menu/batchUpdMenuRtres'
# inter8 = ['E','10001010',4,'1','0']
# resp8 = sendApiRequest(url, headers, inter8)
# json_to_file(resp8,API)

# #
# # 2.1.1.5
# API = '2.1.1.5'
# url = '/rbac/menu/updMenuForRole'
# inter8 = {
#     'operid': '16031',
#     'roleid': 4,
#     'righttype': 'G',
#     'menuids':['101040000','101050000','101070000'],
# }
# resp8 = sendApiRequest(url, headers, inter8)
# json_to_file(resp8,API)

#
# # 2.1.1.6
# API = '2.1.1.6'
# url = '/rbac/api/updApiForRole'
# inter8 = {
#     'operid': '16031'
#
# }
# resp8 = sendApiRequest(url, headers, inter8)
# json_to_file(resp8,API)

# # 2.1.6.2
# API = '2.1.6.2'
# url = '/rbac/operator/alterOperFromKone'
# inter8 = {
#     'operInfoList': [{'operid':'16032','sex':'0'}],
#     'type':'2'
# }
# resp8 = sendApiRequest(url, headers, inter8)
# json_to_file(resp8,API)

# 2.1.8.5
API = '2.1.8.5'
url ='/rbac/role/batchUpdRole'
inter8 = [{'roleId': 4, 'operatorId':16031, 'action':'1'}]

resp8 = sendApiRequest(url, headers, inter8)
json_to_file(resp8,API)

# # 2.1.8.6
# API = '2.1.8.6'
# url ='/rbac/role/updRoleForOper'
# inter8 = {
#     'operid':16031,
#     'roleids':[1,2,3]
# }
# resp8 = sendApiRequest(url, headers, inter8)
# json_to_file(resp8,API)